<template>
  <div class="page-edit">
    <header>
      <i style="font-size: 18px; cursor: pointer; margin-right: 8px" class="el-icon-arrow-left" @click="back"></i>
      <span>添加考核项</span>
    </header>
    <section class="edit-body">
      <div class="form-page">
        <el-form ref="form" :model="form" :rules="rules" label-width="200px">
          <el-col :span="12">
            <el-form-item label="考核表名称" prop="examinationTableName">
              <el-input v-model="form.examinationTableName" placeholder="请输入考核表名称" :readonly="!isEdit"
                :disabled="!isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考核分类" prop="examineType">
              <el-select v-model="form.examineType" placeholder="请选择考核分类" :readonly="!isEdit" :disabled="!isEdit">
                <el-option v-for="dict in examineTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="考核说明" prop="illustrate">
              <el-input v-model="form.illustrate" placeholder="请输入考核说明" :readonly="!isEdit" :disabled="!isEdit"
                type="textarea" rows="3" maxlength="300" show-word-limit />
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <div class="form-page">
        <p class="title-level2">考核项目</p>
        <div>
          <p>总分：0分</p>
          <ItemTable :info="form" type="add" @updateExamineItems="updateExamineItems"/>
        </div>
        <div>
          <el-button @click="addassessmentDialog" style="margin-top: 20px">添加考核项</el-button>
        </div>
      </div>
    </section>
    <!-- 新建考核目标及要点 -->
    <el-dialog :title="editTitle" :visible.sync="assessmentDialog" :close-on-click-modal="false">
      <el-form :inline="true" label-width="120px" label-position="right" :model="addForm" ref="addForm">
        <el-form-item label="考核目标:" prop="examineTarget" :rules="{
          required: true,
          message: '请输入考核目标',
          trigger: 'blur',
        }">
          <el-input v-model="addForm.examineTarget" style="width: 200px" clearable></el-input>
        </el-form-item>
        <el-form-item label="分值:" prop="examineScore" :rules="{
          required: true,
          message: '请输入分值',
          trigger: 'blur',
        }">
          <el-input-number v-model="addForm.examineScore" controls-position="right" :disabled="true"
            style="width: 200px"></el-input-number>
        </el-form-item>
        <div style="border-bottom: 1px dashed; margin-bottom: 20px"></div>
        <template v-if="editParent">
          <div v-for="(item, index) in addForm.children" :key="index" class="reason">
            <div class="jia" v-if="index == addForm.children.length - 1" @click="addDomain">+</div>
            <div class="jian" @click="removeDomain(index)">-</div>
            <el-form-item :label="index + 1 + '考核要点' + ':'" :prop="'children.' + index + '.examineDrop'" :rules="{
              required: true,
              message: '考核要点不能为空',
              trigger: 'blur',
            }">
              <el-input type="textarea" maxlength="500" :show-word-limit="true" :rows="3" v-model="item.examineDrop"
                style="width: 520px" clearable></el-input>
            </el-form-item>
            <el-form-item :label="index + 1 + '考核评价标准' + ':'" :prop="'children.' + index + '.examineStandard'" :rules="{
              required: true,
              message: '考核评价标准不能为空',
              trigger: 'blur',
            }">
              <el-input type="textarea" maxlength="500" :show-word-limit="true" :rows="3" v-model="item.examineStandard"
                style="width: 520px" clearable></el-input>
            </el-form-item>
            <el-form-item :label="index + 1 + '考核点分值' + ':'" :prop="'children.' + index + '.examineDropScore'" :rules="{
              required: true,
              message: '考核点分值不能为空',
              trigger: 'blur',
            }">
                <el-input-number v-model="item.examineDropScore" controls-position="right"
                  style="width: 200px" @change="handleDropScoreChange"></el-input-number>
            </el-form-item>
            <div v-if="index !== addForm.children.length - 1" style="margin-bottom: 15px"></div>
          </div>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button class="cancelBtn" size="small" @click="cancelAssessment">取消</el-button>
        <el-button class="confirmBtn" size="small" type="primary" style="margin-right: 10px" @click="addAssessment">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchSafeAssessment,
  delSafeAssessment,
  delSafeAssessmentItem,
  lookParentItem,
} from "@/api/safetyPerformance"
import { delDrop, addDrop, updateDrop } from "@/api/examine/drop";
import { getTable } from "@/api/examine/table";
import ItemTable from './table.vue'
export default {
  name: "assessment",
  props:['form','examineTypeOptions'],
  components:{ ItemTable },
  data() {
    return {
      rules: {},
      editTitle: "新建考核目标及要点",
      showIndex: false,
      frequency: "1",
      rowKey: "id",
      totalLength: 0,
      currentPage: 1,
      pageSize: 10,
      totalLength1: 0,
      currentPage1: 1,
      pageSize1: 10,
      curHeight: 0,
      curTableHeight: 0,
      curTableHeight1: 0,
      assessmentDialog: false, //添加dialog
      editAssessmentItemDialog: false, //修改子级dialog
      //表格数据
      assessmentTableData: [],
      //表格列数
      assessmentColumns: [
        {
          key: "examineDrop",
          title: "考核目标及要点",
          align: "left",
        },
        {
          key: "examineScore",
          title: "分值",
          width: 100,
          render: (h, params) => {
            return h("span", {}, params.row.examineScore == 0 ? "0" : params.row.examineScore)
          },
        },
        {
          key: "examineDropScore",
          title: "评价标准说明",
        },
        {
          key: "operate",
          title: "操作",
          align: "center",
          width: "250",
          fixed: "right",
          render: (h, params) => {
            return h("div", [
              h(
                "el-button",
                {
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["safetyPerformance:assessment:addPoints"],
                    },
                  ],
                  props: {
                    type: "text",
                    size: "small",
                  },
                  style: {
                    display: params.row.children ? "inline-block" : "none",
                  },
                  on: {
                    click: () => {
                      this.assessmentDialogAgain(params.row)
                    },
                  },
                },
                "新增考核要点"
              ),
              h(
                "el-button",
                {
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["safetyPerformance:assessment:edit"],
                    },
                  ],
                  props: {
                    type: "text",
                    size: "small",
                  },
                  on: {
                    click: () => {
                      this.edit(params.row)
                    },
                  },
                },
                "编辑"
              ),
              h(
                "el-button",
                {
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["safetyPerformance:assessment:remove"],
                    },
                  ],
                  props: {
                    type: "text",
                    size: "small",
                  },
                  on: {
                    click: () => {
                      this.remove(params.row)
                    },
                  },
                },
                "删除"
              ),
            ])
          },
        },
      ],
      //增加表单内容
      addForm: {},
      //   修改子级表单
      editItem: {},
      isAddAgain: false, //点击表格中的新增考核要点，1级内容不可修改
      showAgain: true, //保存并新建按钮显示与否
      //   头部搜索表单
      queryForm: {
        examineDrop: "",
      },
      isEdit: false, //是否编辑
      isPagin: false, //搜索时不显示分页
      editParent: true, //是否为编辑父级,是的话子级不显示
      addKaoHePoint: false, //新增考核要点
      addAll: false, //新增

      parentTitle: "新建考核分类", //父级标题
      parentCategory: false, //父级弹出框显示与否
      showParent: true, //是否显示父级
      //新增父类表单
      addParentForm: {},
      //考核类别
      assessmentCategoryList: [
        {
          value: 1,
          label: "年度",
        },
        {
          value: 2,
          label: "季度",
        },
        {
          value: 3,
          label: "月度",
        },
      ],
      //表格数据
      updateAssessmentTableData: [],
      //ui修改后的列表页
      updateAssessmentColumns: [
        {
          key: "checkName",
          title: "考核分类名称",
          align: "center",
        },
        {
          key: "checkType",
          title: "考核类别",
          align: "center",
          render: (h, params) => {
            return h(
              "span",
              // {},
              this.assessmentCategoryList.find(
                (_) => (_.value == params.row.checkType) == 1
              )?.label
            )
          },
        },
        {
          key: "created",
          title: "创建时间",
          align: "center",
        },
        { key: "companyName", title: "所属公司" },
        {
          key: "operate",
          title: "操作",
          align: "center",
          width: "250",
          fixed: "right",
          render: (h, params) => {
            return h("div", [
              h(
                "el-button",
                {
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["safetyPerformance:assessment:lookItem"],
                    },
                  ],
                  props: {
                    type: "text",
                    size: "small",
                  },
                  on: {
                    click: () => {
                      this.parentLookItem(params.row)
                    },
                  },
                },
                "查看详情"
              ),
              h(
                "el-button",
                {
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["safetyPerformance:assessment:editParent"],
                    },
                  ],
                  props: {
                    type: "text",
                    size: "small",
                  },
                  on: {
                    click: () => {
                      this.editParentInfo(params.row)
                    },
                  },
                },
                "编辑"
              ),
              h(
                "el-button",
                {
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["safetyPerformance:assessment:removeParent"],
                    },
                  ],
                  props: {
                    type: "text",
                    size: "small",
                  },
                  on: {
                    click: () => {
                      this.delParent(params.row.id)
                    },
                  },
                },
                "删除"
              ),
            ])
          },
        },
      ],
      //考核详情数据
      childData: {},
      itemsType:'',
      editItemsTargetName:'',
      editItemsIndex:'',
      editItemsLength:0,
      othersLs:[],
    }
  },
  methods: {
    handleDropScoreChange(val){
      console.log('单个考核点分值',val); 
      let total=0;
      this.addForm.children.forEach(_ => {
        total+=_.examineDropScore;
      })  
      this.addForm.examineScore=total;
      console.log('1111',this.addForm.examineScore);
    },
    updateExamineItems(data){
      console.log('data',data,this.form);
      if(data.type=='delete'){
        let delLists=this.form.examineDropList.filter(_ => _.examineTarget==data.ele).map(_ => _.id);
        let ls=this.form.examineDropList.filter(_ => _.examineTarget!=data.ele);
        this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDrop(delLists);
        }).then(() => {
          this.$set(this.form,'examineDropList',ls);
          this.msgSuccess("删除成功");
        })
      }else{
        this.assessmentDialog=true;
        let ls=this.form.examineDropList.filter(_ => _.examineTarget==data.ele);
        this.othersLs=this.form.examineDropList.filter(_ => _.examineTarget!=data.ele);
        this.addForm=this.handleExamineDropList(ls);
        this.itemsType='edit';
        this.editItemsIndex=data.updatedIndex;
        this.editItemsTargetName=data.ele;
        this.editItemsLength=data.editItemsLength;
        console.log('this.addForm',this.addForm)
      }
    },

    handleExamineDropList(data){
      console.log('data',data);
      let params={};
      if(data&&data.length>0){
        const {examineDrop,examineDropScore,examineStandard,...rest}  = data[0];
        params={
          ...rest
        };
        params.children=data.map(_ => {
          const {examineDrop,examineDropScore,examineStandard,id,...rest}  = _;
          return {
            examineDrop,
            examineDropScore,
            examineStandard,
            id
          }
        })
        console.log('params',params);
      };
      return params;
    },
    // 新建弹出框
    addassessmentDialog() {
      console.log('this.form indfo',this.form);
      this.editTitle = "新建考核目标及要点"
      this.itemsType = 'add';
      this.assessmentDialog = true;
      this.addForm = {
        examinationTableId:this.form.id,
        examineScore:0,
        children: [
          {
            examineDrop: "",
            examineDropScore:0,
            examineStandard:"",
          },
        ],
      }
    },
    // 添加考核要点项
    addDomain() {
      this.addForm.children.push({
        examineDrop: "",
        examineDropScore: "",
      })
    },
    // 删除弹出框中考核要点项
    removeDomain(val) {
      this.addForm.children.forEach((item, index) => {
        console.log('item',item)
        if (this.addForm.children.length > 1 && val === index) {
          this.addForm.children.splice(val, 1);
          if(item.id){ // 调用删除接口
            let delLists=[item.id];
            delDrop(delLists).then(res => {
              console.log('res',res);
            });
            // this.form.examineDropList = this.form.examineDropList.filter(_ => _.id!=item.id);
          }
        }
      })
    },
    // 考核项table表格
    getDetails(id){
      getTable(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "编辑考核点";
      })
    },
    // 包装添加的保存的数据
    assembleAddForm(){
      const { children,...rest } = this.addForm;
      let lists=[];
      if(this.addForm.children&&this.addForm.children.length>0){
        lists=this.addForm.children.map(_ => {
          return {
            ...rest,
            ..._,
            id:_.id??null,
            factoryId:this.$store.getters.factoryId,
          }    
        })
      }
      console.log('lists',lists);
      return lists;
    },
    // 保存
    addAssessment() {
      // 只是保存在前端页面
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let dropLists=this.form.examineDropList;
          console.log('dropLists',dropLists);
          console.log('this.addForm',this.addForm);
          let ls = this.assembleAddForm();
          if(this.itemsType=='edit'){ // 编辑---对相同的数据根据第一个下标进行替换
            console.log('this.edit',this.editItemsTargetName,this.editItemsIndex,this.editItemsLength);
            dropLists.splice(this.editItemsIndex,this.editItemsLength,ls);
            this.form.examineDropList=dropLists.flat();      
            console.log('本次编辑后的数据ls-------------',ls);
            console.log('所有的this.form.examineDropList',this.form.examineDropList);
            // 处于编辑状态
            updateDrop(this.form.examineDropList).then((res) => {
              if (res.code == 200) {
                this.assessmentDialog=false;
                this.getDetails(this.form.id);
              }
            })
          }else{  // 新增
            this.form.examineDropList=(this.form.examineDropList??[]).concat(ls);
            addDrop(ls).then((res) => {
              if (res.code == 200) { 
                this.assessmentDialog=false;
                this.getDetails(this.form.id);
              }
            })
          }
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },
    // 取消
    cancelAssessment() {
      this.assessmentDialog = false
      this.$refs.addForm.resetFields()
      //   this.addForm = {};
    },
    // 删除
    remove(params) {
      let that = this
      if (params.children) {
        this.$confirm("确认删除？", {
          showClose: false,
        }).then((_) => {
          delSafeAssessment(params.id).then((res) => {
            console.log("删除父级", res)
            if (res.code == "00x0") {
              // this.getList();
              lookParentItem(that.childData.id).then((res) => {
                if (res.code == 200) {
                  that.assessmentTableData = res.data
                }
              })
            }
          })
        })
      } else {
        this.$confirm("确认删除？", {
          showClose: false,
        }).then((_) => {
          console.log("parmas", params)
          delSafeAssessmentItem(params).then((res) => {
            console.log("删除子集", res)
            if (res.code == "00x0") {
              // this.getList();
              lookParentItem(that.childData.id).then((res) => {
                if (res.code == 200) {
                  that.assessmentTableData = res.data
                }
              })
            }
          })
        })
      }
    },
    handleCurrentChange(val) {
      this.currentPage = val
      let params = {}
      params.current = this.currentPage
      params.size = this.pageSize
      params.frequency = this.frequency
      searchSafeAssessment(params).then((res) => {
        if (res.code == "00x0") {
          this.assessmentTableData = res.data.records
          this.totalLength = res.data.total
        }
      })
    },
    back() {
      this.$emit('closeAddItem')
    },
  },
}
</script>

<style>
.el-tooltip__popper {
  max-width: 60%;
}

.reason {
  position: relative;
  background-color: #f3f3f3;
  padding-top:20px;
}

.reason>.jian {
  position: absolute;
  left: 672px;
  z-index: 99999;
  font-size: 14px;
  border: 1px solid #999999;
  border-radius: 2px;
  width: 16px;
  height: 16px;
  line-height: 8px;
  text-align: center;
  padding: 2px;
  cursor: pointer;
}

.reason>.jia {
  position: absolute;
  left: 653px;
  z-index: 99999;
  font-size: 14px;
  border: 1px solid #999999;
  border-radius: 2px;
  width: 16px;
  height: 16px;
  line-height: 8px;
  text-align: center;
  padding: 2px;
  cursor: pointer;
}
::v-deep .el-dialog .el-dialog__body{
  padding:20px !important;
}
</style>


